package com.bulletelc.apollopre.module.main.center.intention;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.bigkoo.pickerview.OptionsPickerView;
import com.bulletelc.apollopre.MyApplication;
import com.bulletelc.apollopre.R;
import com.bulletelc.apollopre.entity.JsonBean;
import com.bulletelc.apollopre.framework.MVPBaseActivity;
import com.bulletelc.apollopre.module.user.LoginMainActivity;
import com.bulletelc.apollopre.utils.GetJsonDataUtil;
import com.bulletelc.apollopre.utils.KeyboardUtil;
import com.bulletelc.apollopre.utils.RegExUtil;
import com.bulletelc.apollopre.utils.ToastUtil;
import com.bulletelc.apollopre.widget.FoolBar;
import com.google.gson.Gson;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by Administrator on 2018/5/15.
 * 意向单提交界面
 */

public class IntentionActivity extends MVPBaseActivity<IntentionContract.View, IntentionPresenter> implements IntentionContract.View,
        View.OnClickListener, FoolBar.ClickCallback {

    // views
    private EditText etName, etMobile, etContract, etDetail;
    private TextView tvAddress;
    private Button btnCommit;
    private FoolBar flBar;

    // data
    private static final int MSG_LOAD_SUCCESS = 0x0002;
    private static final int MSG_LOAD_FAILED = 0x0003;
    private int addressId = 0; // 地址ID
    final static int REQUEST_CODE = 1;
    private String provinceId; // 省份ID
    private String cityId; // 城市ID
    private String districtId; // 区(县)ID
    private boolean load = false; // 地区数据是否加载好
    private List<JsonBean> options1Items = new ArrayList<>();
    private List<List<JsonBean.CityListBean>> options2Items = new ArrayList<>();
    private List<List<List<JsonBean.CityListBean.DistrictListBean>>> options3Items = new ArrayList<>();

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case MSG_LOAD_SUCCESS:
                    load = true;
                    break;

                case MSG_LOAD_FAILED:
                    Toast.makeText(IntentionActivity.this, "地区数据解析错误", Toast.LENGTH_SHORT).show();
                    break;
            }
        }
    };

    @Override
    public int getLayoutRes() {
        return R.layout.intention_activity;
    }

    @Override
    public void assignViews() {
        etName = findView(R.id.etName);
        etMobile = findView(R.id.etMobile);
        tvAddress = findView(R.id.tvAddress);
        etContract = findView(R.id.etContract);
        etDetail = findView(R.id.etDetail);
        btnCommit = findView(R.id.btnCommit);
        flBar = findView(R.id.flBar);
    }

    @Override
    public void setListener() {
        tvAddress.setOnClickListener(this);
        flBar.setClickCallback(this);
        btnCommit.setOnClickListener(this);
    }

    @Override
    public void initData(Bundle savedInstanceState) {
        flBar.setTitle("我的意向");
        loadData();
    }

    @Override
    protected IntentionPresenter createPresenter() {
        return new IntentionPresenter();
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.tvAddress:
                KeyboardUtil.closeKeyboard(this);
                if (load) {
                    ShowPickerView();
                } else {
                    Toast.makeText(this, "地区数据加载中，请您稍等片刻...", Toast.LENGTH_LONG).show();
                }
                break;
            case R.id.btnCommit:
                String token = MyApplication.getToken();
                if (token.length() > 0 && null != token) {
                    presenter.checkAddress(cityId);
                } else {
                    //未登录
                    ToastUtil.showShortToast(this, "请先登录");
                    startActivity(new Intent(this, LoginMainActivity.class));
                }
                break;
        }
    }

    /**
     * 开启线程 加载本地全国数据
     */
    private void loadData() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                initJsonData();
            }
        }).start();
    }

    /**
     * 加载本地全国数据
     */
    private void initJsonData() {
        String jsonData = new GetJsonDataUtil().getJson(this, "address.json");//获取assets目录下的json文件数据
        List<JsonBean> jsonBeans = parseData(jsonData);
        options1Items = jsonBeans;
        for (int i = 0; i < jsonBeans.size(); i++) {//遍历省份
            List<JsonBean.CityListBean> cityListBeans = new ArrayList<>();//该省的城市列表（第二级）
            List<List<JsonBean.CityListBean.DistrictListBean>> districtListBeans = new ArrayList<>();//该省的所有地区列表（第三极）

            for (int c = 0; c < jsonBeans.get(i).getCityList().size(); c++) {//遍历该省份的所有城市
                JsonBean.CityListBean cityListBean = jsonBeans.get(i).getCityList().get(c);
                cityListBeans.add(cityListBean);//添加城市

                List<JsonBean.CityListBean.DistrictListBean> districtListBeans1 = new ArrayList<>();//该城市的所有地区列表

                //如果无地区数据，建议添加空字符串，防止数据为null 导致三个选项长度不匹配造成崩溃
                if (jsonBeans.get(i).getCityList().get(c).getDistrictList() == null || jsonBeans.get(i).getCityList().get(c).getDistrictList().size() == 0) {
                    districtListBeans1.add(null);
                } else {

                    for (int d = 0; d < jsonBeans.get(i).getCityList().get(c).getDistrictList().size(); d++) {//该城市对应地区所有数据
                        JsonBean.CityListBean.DistrictListBean district = jsonBeans.get(i).getCityList().get(c).getDistrictList().get(d);
                        districtListBeans1.add(district);//添加该城市所有地区数据
                    }
                }
                districtListBeans.add(districtListBeans1);//添加该省所有地区数据
            }

            /**
             * 添加城市数据
             */
            options2Items.add(cityListBeans);

            /**
             * 添加地区数据
             */
            options3Items.add(districtListBeans);
        }


        handler.sendEmptyMessage(MSG_LOAD_SUCCESS);

    }

    /**
     * Gson 解析
     *
     * @param result
     * @return
     */
    private List<JsonBean> parseData(String result) {
        List<JsonBean> detail = new ArrayList<>();
        try {
            JSONArray data = new JSONArray(result);
            Gson gson = new Gson();
            for (int i = 0; i < data.length(); i++) {
                JsonBean entity = gson.fromJson(data.optJSONObject(i).toString(), JsonBean.class);
                detail.add(entity);
            }
        } catch (Exception e) {
            e.printStackTrace();
            handler.sendEmptyMessage(MSG_LOAD_FAILED);
        }
        return detail;
    }

    /**
     * 弹出选择器
     */
    private void ShowPickerView() {

        OptionsPickerView pvOptions = new OptionsPickerView.Builder(this, new OptionsPickerView.OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int options2, int options3, View v) {
                //返回的分别是三个级别的选中位置
                String tx=null;
                if (options3Items.get(options1).get(options2).get(options3) != null) {
                    tx = options1Items.get(options1).getName() + " " +
                            options2Items.get(options1).get(options2).getName() + " " +
                            options3Items.get(options1).get(options2).get(options3).getName();

                    provinceId = String.valueOf(options1Items.get(options1).getId());
                    cityId = String.valueOf(options2Items.get(options1).get(options2).getId());
                    districtId = String.valueOf(options3Items.get(options1).get(options2).get(options3).getId());
                } else {
                    tx = options1Items.get(options1).getName() + " " +
                            options2Items.get(options1).get(options2).getName() ;

                    provinceId = String.valueOf(options1Items.get(options1).getId());
                    cityId = String.valueOf(options2Items.get(options1).get(options2).getId());
                    //districtId = String.valueOf(options3Items.get(options1).get(options2).get(options3).getId());
                }


                tvAddress.setText(tx);

            }
        })

                .setTitleText("城市选择")
                .setDividerColor(Color.BLACK)
                .setTextColorCenter(Color.BLACK) //设置选中项文字颜色
                .setContentTextSize(20)
                .build();

        /*pvOptions.setPicker(options1Items);//一级选择器
        pvOptions.setPicker(options1Items, options2Items);//二级选择器*/
        pvOptions.setPicker(options1Items, options2Items, options3Items);//三级选择器
        pvOptions.show();
    }


    @Override
    public void onLeftClick() {
        finish();
    }

    @Override
    public void onRightClick() {

    }

    @Override
    public void onSuccessCommit() {
        ToastUtil.showShortToast(this, "提交成功");
        this.finish();
    }

    @Override
    public void onErrorCommit(String error) {
        ToastUtil.showShortToast(this, R.string.network_msg);
    }

    @Override
    public void onFailCommit(String fail) {
        ToastUtil.showShortToast(this, fail);
    }

    @Override
    public void onSuccessCheckAddress(boolean b) {
        if (b) {
            commit();
        }

    }

    @Override
    public void onFailCheckAddress(String fail) {
        ToastUtil.showLongToast(this, fail);
    }

    @Override
    public void onErrorCheckAddress(String error) {
        ToastUtil.showShortToast(this, R.string.network_msg);
    }

    private void commit() {

        String json = null;
        String name = etName.getText().toString().trim();
        String mobile = etMobile.getText().toString().trim();
        String address = tvAddress.getText().toString().trim();
        String contract = etContract.getText().toString().trim();
        String detail = etDetail.getText().toString().trim();

        if ("".equals(name)) {
            ToastUtil.showShortToast(this, R.string.hint_input_nickname);
            return;
        }
        if (!RegExUtil.isMobileExact(mobile)) {
            ToastUtil.showShortToast(this, R.string.hint_input_correct_mobile);
            return;
        }
        if ("".equals(address)) {
            ToastUtil.showShortToast(this, "请先选择地址");
            return;
        }
        if ("".equals(contract)) {
            ToastUtil.showShortToast(this, "请先填写详细地址");
            return;
        }
        if ("".equals(detail)) {
            ToastUtil.showShortToast(this, "填写点内容吧");
            return;
        }
        JSONObject object = new JSONObject();
        try {
            object.put("type", 1);
            object.put("customer_id", MyApplication.getUserId());
            object.put("province_id", provinceId);
            object.put("city_id", cityId);
            object.put("district_id", districtId);
            object.put("contact_man", name);
            object.put("contact_phone", mobile);
            object.put("address", address + " " + contract);
            object.put("cms_case_id", 0);
            object.put("memo", detail);
            json = object.toString();
        } catch (JSONException e) {
            e.printStackTrace();
        }
        presenter.commit(json);

    }

}
